package com.yitiao.multithread;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

// 自旋锁
public class SpinLockDemo {
    AtomicReference<Thread> reference=new AtomicReference<>();
    public void MyLock(){
        while (!reference.compareAndSet(null,Thread.currentThread())){
//            System.out.println(Thread.currentThread().getName()+"======持有锁");
        }
    }

    public void MyUNLock(){
        reference.compareAndSet(Thread.currentThread(),null);
        System.out.println("======解锁");

    }
    public static void main(String[] args) {
        SpinLockDemo spinLockDemo = new SpinLockDemo();
        new Thread(()->{
            System.out.println("--------t1 come in");
            spinLockDemo.MyLock();
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            spinLockDemo.MyUNLock();
        },"t1").start();

        new Thread(()->{
            System.out.println("---------t2 come in");
            spinLockDemo.MyLock();
            spinLockDemo.MyUNLock();
        },"t2").start();
    }
}
